package com.dadibadi.core.user.service;

import com.dadibadi.core.dao.entity.UserInfoTab;
import com.dadibadi.core.dao.mapper.UserInfoMapper;
import com.dadibadi.core.user.qo.UserInfoEditQO;
import com.dadibadi.core.work.qo.WorkInfoIdQO;
import com.dadibadi.core.work.service.WorkInfoService;
import com.venusoft.developer.common.utils.ConvertUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserInfoService {
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    WorkInfoService workInfoService;




    /**
     * 用户信息更新，如果id存在，则更新，若不存在，则插入
     *
     * @param qo
     * @return
     */
    public UserInfoTab saveUserInfo(UserInfoEditQO qo) {
        UserInfoTab userInfoTab = userInfoMapper.selectById(qo.getUserId());
        if (userInfoTab == null) {
            UserInfoTab userInfoTab1 = new UserInfoTab();
            userInfoTab1.setUserId(qo.getUserId());
            userInfoTab1.setAvatar(qo.getAvatar());
            userInfoTab1.setNickName(qo.getNickName());
            userInfoTab1.setSelfIntro(qo.getSelfIntro());
            userInfoTab1.setMemberFlag(0);
            userInfoMapper.insert(userInfoTab1);
            return userInfoTab1;
        } else {
            userInfoTab.setAvatar(qo.getAvatar());
            userInfoTab.setNickName(qo.getNickName());
            userInfoTab.setSelfIntro(qo.getSelfIntro());
            userInfoTab.setUserId(qo.getUserId());
            userInfoMapper.updateById(userInfoTab);
            return userInfoTab;
        }
    }

    public void updateArticleCount(UserInfoEditQO qo) {
        if(qo.getArticleCount()==null)
        {
            qo.setArticleCount(0);
        }
        int count = workInfoService.getUserArticleCount
                (workInfoService.getWorkInfoByUser(ConvertUtil.convert(qo, WorkInfoIdQO.class)));
        UserInfoTab userInfoTab = userInfoMapper.selectById(qo.getUserId());
        userInfoTab.setArticleCount(count);
        userInfoMapper.updateById(userInfoTab);
    }

    public void updateUserMemberFlag(String userId){
        UserInfoTab userInfoTab=new UserInfoTab();
        userInfoTab=userInfoMapper.selectById(userId);
        userInfoTab.setMemberFlag(1);
        userInfoMapper.updateById(userInfoTab);
    }

}
